package com.example.spgl.Filter;


import com.alibaba.fastjson.JSON;
import com.example.spgl.Common.BaseContext;
import com.example.spgl.entity.Result;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;


import java.io.IOException;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;


@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("拦截到请求:{}", requestURI);

        String[] urls = new String[]{
                "/user/login",
                "/user/register",
                "/common/upload",
                "/common/download",
                "/file/upload",
                "/file/download"
        };

        boolean check = check(urls, requestURI);

        //3.不需要处理，直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        // 4.判断登录状态，如果已经登录，直接放行
        if(request.getSession().getAttribute("userInfo")!=null){
            log.info("用户已登录,用户id为:{}",request.getSession().getAttribute("userInfo"));
            String username = (String) request.getSession().getAttribute("userInfo");

            BaseContext.setCurrentId(username);
            filterChain.doFilter(request,response);
            return;
        }

        log.info("用户未登录");
        // 5.如果未登录则返回未登录结果,通过客户端输出方式来返回页面的响应数据
        response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(Result.error("NOTLOGIN")));
        return;

    }



    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }

        return false;
    }
}
